﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using App.Utilities.Web.Handlers;
using System.Data;
using CRMBiz;
using Newtonsoft.Json;
using CRMBiz.AM;
using CRMWeb.Utilities.Context;

namespace CRMWeb.WebServices
{
    /// <summary>
    /// Summary description for LoanForm
    /// </summary>
    public class LoanForm : BaseHandler
    {
        public override void OnMethodInvoke(OnMethodInvokeArgs e)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
            context.Response.Cache.SetExpires(DateTime.MinValue);
            context.Response.Cache.SetNoStore();
            //e.Cancel = true;
            SetResponseContentType(ResponseContentTypes.HTML);
        }

        public override void AfterMethodInvoke(object result)
        {
            base.AfterMethodInvoke(result);
        }

        #region Summary
        //Get Loans
        public void GetAllLoans()
        {
            try
            {
                var pageIndex = string.IsNullOrEmpty(context.Request["page"]) ? 1 : int.Parse(context.Request["page"]);
                var pageSize = string.IsNullOrEmpty(context.Request["rows"]) ? 10 : int.Parse(context.Request["rows"]);

                var searchtext = string.IsNullOrEmpty(context.Request.QueryString["searchtext"]) ? "" : context.Request.QueryString["searchtext"];
                var conditiontext = string.IsNullOrEmpty(context.Request.QueryString["conditiontext"]) ? "" : context.Request.QueryString["conditiontext"];
                var sortText = string.IsNullOrEmpty(context.Request.QueryString["sortCondition"]) ? "" : context.Request.QueryString["sortCondition"];

                DataSet ds = LoanInformationHandler.GetLoanDetails(pageIndex, pageSize, searchtext, conditiontext, sortText);
                var total = (ds.Tables[0].Rows.Count > 0) ? Convert.ToInt32(ds.Tables[0].Rows[0]["Total"]) : 0;
                string strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                strJson = "{\"total\":\"" + total.ToString() + "\",\"rows\":" + strJson + "}";
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        //Get All PaymentPeriod
        public void GetAllPaymentPeriod()
        {
            string strJson = null;
            try
            {
                DataSet ds = LoanInformationHandler.GetAllPaymentPeriod();
                strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        //Get assessment last result:
        public void GetAssessmentLastResults()
        {
            string strJson = null;
            try
            {
                DataSet ds = LoanInformationHandler.GetAssessmentLastResult();
                strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        //Get All Banks
        public void GetLastResult()
        {
            string strJson = null;
            try
            {
                DataSet ds = LoanInformationHandler.GetLastResult();
                strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        #endregion

      

        public void SearchLoanDetailByAppID(int app_id)
        {
            try
            {
                DataTable dt = LoanInformationHandler.SearchLoanDetailByAppID(app_id);
                string strJson = JsonConvert.SerializeObject(dt);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void SearchBankDetailByLoanID(int LoanID)
        {
            try
            {
                DataTable dt = LoanInformationHandler.SearchBankDetailByLoanID(LoanID);
                string strJson = JsonConvert.SerializeObject(dt);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void SearchLoanDetailByLoanID(int LoanID)
        {
            try
            {
                DataTable dt = LoanInformationHandler.SearchLoanDetailByLoanID(LoanID);
                string strJson = JsonConvert.SerializeObject(dt);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        //Check LenderStaus to invoke the AddLoan or SaveLoan function:
        public void CheckLenderStatus(int app_id)
        {
            try
            {
                DataTable dt = LoanInformationHandler.CheckLenderStatus(app_id);
                string strJson = JsonConvert.SerializeObject(dt);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        //user defined function
        #region private method For Loan
        public void AddLoanInfoFromAsessment(string app_id, string LoanNumber, string Lender, string CreateDate,string EditDate, string LoanStatus, string LastResult, string Memo)
        {
            try
            {
                int loanid = LoanInformationHandler.AddLoanInfoFromAsessment(app_id, LoanNumber, Lender, CreateDate,EditDate, LoanStatus, LastResult,Memo);
                context.Response.Write(loanid);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void UpdateLoanInfoFromAsessment(string app_id, string LoanNumber, string Lender, string EditDate, string LastResult,string Memo)
        {
            try
            {
                int loanid = LoanInformationHandler.UpdateLoanInfoFromAsessment(app_id, LoanNumber, Lender, EditDate, LastResult,Memo);
                context.Response.Write(loanid);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void UpdateLoanInfo(string LoanID, string LoanNumber, string Lender, string Purpose, string Product, string Type, string DrawDownDate, string LoanTerm, string FirstPaymentDue, string PaymetFrequecy, string LowerRate, string HigherRate, string InterestMethod, string LoanAmount, string DishonorFee, string DefaultNotice, string EditDate)
        {
            try
            {
                int retval = LoanInformationHandler.UpdateLoanInfo(LoanID, LoanNumber, Lender, Purpose, Product, Type, DrawDownDate, LoanTerm, FirstPaymentDue, PaymetFrequecy, LowerRate, HigherRate, InterestMethod, LoanAmount, DishonorFee, DefaultNotice, EditDate);
                context.Response.Write(retval);
            }
            catch (Exception ex) 
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void UpdateLoanInfo1(string LoanID, string Memo, string EditDate)
        {
            try
            {
                int retval = LoanInformationHandler.UpdateLoanInfo(LoanID, Memo, EditDate);
                context.Response.Write(retval);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void AddPaymentSchedule(int LoanID, string paraPurpose, string paraProduct, string paraType, string paraSettlementDate,
                                             int paraTerm, string paraFirstPaymentDate, string paraPaymetFrequecy, decimal paraAnnumInterestRate,
                                             string paraInterestMethod, decimal paraLoanAmount)
        {
            try
            {
                int retval = LoanInformationHandler.AddPaymentSchedule(LoanID, paraPurpose, paraProduct, paraType, paraSettlementDate, paraTerm, paraFirstPaymentDate, paraPaymetFrequecy, paraAnnumInterestRate, paraInterestMethod, paraLoanAmount);
                context.Response.Write(retval);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void SimpleInterestPaymentScheduleByRepayment(int LoanID, decimal repaymentAmount, string paymentperiod, DateTime firstPaymentDate)
        {
            try
            {
                int intReturnValue = LoanInformationHandler.SimpleInterestPaymentScheduleByRepayment(LoanID, repaymentAmount, paymentperiod, firstPaymentDate);
                //string strJson = JsonConvert.SerializeObject(dt);
                context.Response.Write(intReturnValue);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void AddSinglePayment(int LoanID, string SingleRepayment, string SingleFirstPaymentDue)
        {
            try
            {
                int retval = LoanInformationHandler.AddSinglePayment(LoanID, SingleRepayment, SingleFirstPaymentDue);
                context.Response.Write(retval);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void DisplayPaymentSchedule(int LoanID, string paraPurpose, string paraProduct, string paraType, string paraSettlementDate,
                                           int paraTerm, string paraFirstPaymentDate, string paraPaymetFrequecy, decimal paraAnnumInterestRate,
                                           string paraInterestMethod, decimal paraLoanAmount)
        {
            try
            {
                List<PaymentEntity> dt = CalPayment.SimpleInterestPaymentScheduleByTerm(LoanID, paraPurpose, paraProduct, paraType, paraSettlementDate, paraTerm, paraFirstPaymentDate, paraPaymetFrequecy, paraAnnumInterestRate, paraInterestMethod, paraLoanAmount);
                string strJson = JsonConvert.SerializeObject(dt);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void CalculateRepayment(int LoanID, string paraPurpose, string paraProduct, string paraType, string paraSettlementDate,
                                                      int paraTerm, string paraFirstPaymentDate, string paraPaymetFrequecy, decimal paraAnnumInterestRate,
                                                      string paraInterestMethod, decimal paraLoanAmount)
        {
            try
            {
                DataTable dt = CalPayment.CalculatePaymentbyFre(LoanID, paraPurpose, paraProduct, paraType, paraSettlementDate, paraTerm, paraFirstPaymentDate, paraPaymetFrequecy, paraAnnumInterestRate, paraInterestMethod, paraLoanAmount);
                string strJson = JsonConvert.SerializeObject(dt);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        #endregion

        #region private method For Bank

        public void AddBankInfoFromAsessment(int LoanID, string LoanType)
        {
            try
            {
                int intretvalue = LoanInformationHandler.AddBankInfoFromAsessment(LoanID, LoanType);
                context.Response.Write(intretvalue);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void UpdateBankInfo(string BankName, string AccountNo, string BSB, int LoanID, string LoanType, string AccountHolder)
        {
            try
            {
                int intretvalue = LoanInformationHandler.UpdateBankInfo(BankName, AccountNo, BSB, LoanID, LoanType, AccountHolder);
                context.Response.Write(intretvalue);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        #endregion
         
        #region methods for contract effective
        public void UpdateDDRAccount(string NewDDRDate, string LoanID, string LastName,string FirstName,string Address1,string Suburb,string State,string PostCode,string Email,string MobilePhone)
        {
            string strJson = null;
            try
            {
                DataSet ds = LoanInformationHandler.UpdateDDRAccount(NewDDRDate, LoanID, LastName, FirstName, Address1, Suburb, State, PostCode, Email, MobilePhone);
                strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void UpdateBankAccDate(string BankAccDate, string LoanID)
        {
            string strJson = null;
            try
            {
                DataSet ds = LoanInformationHandler.UpdateBankAccDate(BankAccDate, LoanID);
                strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void UpdatePaymentSchDate(string PaymentSchDate, string LoanID, string CustomerRefNo)
        {
            string strJson = null;
            try
            {
                if (CustomerRefNo != null && CustomerRefNo != "")
                {
                    DataSet ds = LoanInformationHandler.UpdatePaymentSchDate(PaymentSchDate, LoanID, CustomerRefNo);
                    strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                    context.Response.Write(strJson);
                }
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void UpdateEffectiveDate(string EffectiveDate, string LoanID, string DoubleChecked, string LoanStatus)
        {
            try
            {
                int intretvalue = LoanInformationHandler.UpdateEffectiveDate(EffectiveDate, LoanID, DoubleChecked, LoanStatus);
                context.Response.Write(intretvalue);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        #endregion

        public void GetSingleAccountidAppid(int account_id)
        {
            try
            {
                DataTable dt = LoanInformationHandler.GetSingleAccountidAppid(account_id);
                string strJson = JsonConvert.SerializeObject(dt);
                if (dt.Rows.Count > 0)
                {
                    HttpContext.Current.Session["AppID"] = dt.Rows[0]["app_id"].ToString();
                    HttpContext.Current.Session["AccountID"] = dt.Rows[0]["account_id"].ToString();
                }
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
        }

    }
}